import axios from 'axios';
import {ElMessage} from 'element-plus'

axios.defaults.baseURL = config.baseUrl;
axios.defaults.timeout = config.timeout;
axios.defaults.withCredentials = true

// request interceptor
axios.interceptors.request.use(config => {
        //before send
        console.log('request:', config.url, config.data);
        if (config.data.token === "") {
            config.data.token = sessionStorage.getItem('token')
        }
        return config;
    },
    error => {
        //catch error
        console.log(error)
        return Promise.reject(error);
    });

//response interceptor
axios.interceptors.response.use(
    //event when status code in 2xx
    response => {
        console.log('response:', response.config.url, response.data);
        const result = response.data
        if (result.code === 0) {
            ElMessage.success({message: result.msg, duration: 100})
            return result.res;
        } else {
            ElMessage.warning(result.msg || result.message)
            return null
        }
    },
    //event when status code out of 2xx
    error => {
        ElMessage.error(error)
        return Promise.reject(error);
    });

export default axios;
